/*
 * Copyright (C) 2009-2018 Hangzhou 2Dfire Technology Co., Ltd. All rights reserved
 */
package com.ws.soa.consumer.service;

import com.google.common.base.Preconditions;
import com.ws.soa.consumer.dao.mapper.AccountMapper;
import com.ws.soa.consumer.domain.AccountDO;
import com.ws.soa.consumer.dto.AccountLoginDTO;
import com.ws.soa.consumer.dto.AccountRegisterDTO;
import com.ws.soa.consumer.payment.constant.Constants;
import com.ws.soa.consumer.session.UserSessionStorage;
import com.ws.soa.consumer.util.UUIDUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * AccountService
 *
 * @author luobosi@2dfire.com
 * @since 2019-03-06
 */
@Service
public class AccountService {

  @Resource
  private AccountMapper accountMapper;

  @Resource
  private SessionStorageClientService sessionStorageClientService;

  public boolean save(AccountRegisterDTO registerDTO, boolean isSaveSession) {
    Preconditions.checkArgument(null != registerDTO);
    AccountDO accountDO = this.dtoToDO(registerDTO);
    this.saveToSession(accountDO);
    return this.accountMapper.insert(accountDO) > 0;
  }

  private void saveToSession(AccountDO accountDO) {
    UserSessionStorage sessionStorage = new UserSessionStorage();
    sessionStorage.setMemberId(accountDO.getId());
    sessionStorage.setNickName(accountDO.getUsername());
    sessionStorage.setHeadUrl(accountDO.getAvatar());
    this.sessionStorageClientService.saveUserSessionStorage(accountDO.getId(), sessionStorage);
  }

  /**
   * 根据主键id 查找用户
   *
   * @param id id
   * @return account
   */
  public AccountDO findAccountById(String id) {
    Preconditions.checkArgument(StringUtils.isNoneEmpty(id));
    return this.accountMapper.selectById(id);
  }

  /**
   * 根据主键id 查找用户
   *
   * @param mobile 手机号
   * @return account
   */
  public AccountDO findAccountByMobile(String mobile) {
    Preconditions.checkArgument(StringUtils.isNoneEmpty(mobile));
    return this.accountMapper.selectByMobile(mobile);
  }

  /**
   * 修改用户状态
   *
   * @param id         id
   * @param userStatus 用户状态
   * @return true/false
   */
  public boolean updateAccountStatus(String id, Integer userStatus) {
    Preconditions.checkArgument(StringUtils.isNoneEmpty(id));
    Preconditions.checkArgument(null != userStatus);
    return this.accountMapper.updateAccountStatus(id, userStatus, System.currentTimeMillis()) > 0;
  }

  private AccountDO dtoToDO(AccountRegisterDTO registerDTO) {
    AccountDO accountDO = new AccountDO();
    accountDO.setId(UUIDUtil.getUUID());
    accountDO.setMobile(registerDTO.getMobile());
    accountDO.setUsername(registerDTO.getUsername());
    return accountDO;
  }
}
